﻿using AutoMapper;
using MediatR;
using RBAC.Domain.RBAC;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Role;

namespace RBAC.Write.Api.Application.Handler.Role
{
    public class UpdateRoleHandler : IRequestHandler<UpdateRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly IBaseRepository<RolePermissionModel> rolepermissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateRoleHandler> logger;

        public UpdateRoleHandler(IBaseRepository<RoleModel> roleRepository, IBaseRepository<RolePermissionModel> rolepermissionRepository, IMapper mapper, ILogger<UpdateRoleHandler> logger)
        {
            this.roleRepository = roleRepository;
            this.rolepermissionRepository = rolepermissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 更新角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();

            var role = roleRepository.GetALL().FirstOrDefault(x => x.Id == request.Id);
            var rolepermission = rolepermissionRepository.GetALL().Where(x => x.RoleId == request.Id).ToList();
            foreach (var item in rolepermission)
            {
                item.IsDeleted = true;
                rolepermissionRepository.Update(item);
            }
            var data = mapper.Map(request, role);
            var r = roleRepository.Update(data);
            foreach (var item in request.PermissionIds)
            {
                var permission = new RolePermissionModel()
                {
                    RoleId = role.Id,
                    PermissionId = item,
                };
                var r2 = rolepermissionRepository.Update(permission);
            }
            if (r > 0)
            {
                res.Data = r;
                res.Code = APIEnums.Success;
                res.Msg = "修改成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = APIEnums.Fail;
                res.Msg = "修改失败";
                return Task.FromResult(res);
            }

        }
    }
}
